package org.cy.evolution.net.http.converter.json;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializeConfig;
import com.alibaba.fastjson.serializer.SerializerFeature;

import java.io.IOException;

import okhttp3.MediaType;
import okhttp3.RequestBody;
import retrofit2.Converter;

public class FastJsonRequestBodyConverter<T> implements Converter<T, RequestBody> {



    private MediaType mType;
    private SerializeConfig config;
    private SerializerFeature[] features;

    public FastJsonRequestBodyConverter(MediaType mType, SerializeConfig config, SerializerFeature... features) {
        this.mType = mType;
        this.config = config;
        this.features = features;
    }

    @Override
    public RequestBody convert(T value) throws IOException {
        byte[] content;
        if (null != config) {
            if (null != features && features.length > 0) {
                content = JSON.toJSONBytes(value, config, features);
            } else {
                content = JSON.toJSONBytes(value, config);
            }
        } else {
            if (null != features && features.length > 0) {
                content = JSON.toJSONBytes(value, features);
            } else {
                content = JSON.toJSONBytes(value);
            }
        }
        return RequestBody.create(mType, content);
    }
}
